/*****  Component, by Ben Bi <prince.bi@gmail.com>  created at: 12/23/2009 4:10:45 PM  *****/

/********   Notes:  *******
 *  Two tags need to be replaced with the module name, they are:
 *  cottonOrderGoodsItem
 *  CottonOrderGoodsItem
 */



/***** variables declartion section, begin *****/
var cottonOrderGoodsItemInputMode = wacFormInputMode.add;
var cottonOrderGoodsItemObj = {};
var cottonOrderObj = {};

/***** variables declartion section, end *****/

/***** init section, begin *****/
$(document).ready(
    function() {
        initCottonOrderGoodsItemFormDialog();

        initCottonOrderGoodsItemForm();

        bindCottonOrderGoodsItemEvents();
    }
);

function bindCottonOrderGoodsItemEvents()
{
    $("#cottonOrderGoodsItemFormDialog").bind('dialogopen', function(event, ui)
    {
        initCottonOrderGoodsItemFormData();
//        wacDebugLog("calling " + moduleName + ":" + wacModelObj.cottonOrderGoodsItem.name);//
    });

    $("#cottonOrderGoodsItemFormDialog").bind('dialogclose', function(event, ui)
    {
        $.validationEngine.closePrompt(".formError", true);
    });

    $("#cottonOrderGoodsItem_btnSubmit").bind('click', function (e)
    {
        submitCottonOrderGoodsItemForm();
    });

    $("#cottonOrderGoodsItem_btnClose").bind('click', function (e)
    {
        $("#cottonOrderGoodsItemFormDialog").dialog('close');
    });

    // fix dialog div didnt remove bug, remove it by this way
    $('#appStorehouseRightPane').bind('tabsremove', function(event, ui) {
        if(ui.panel.id == "t1012")
        {
            $("div[aria-labelledby='ui-dialog-title-cottonOrderGoodsItemFormDialog']").remove();
            $("#cottonOrderGoodsItemFormDialog").remove();
        }
    });
}


function initCottonOrderGoodsItemFormDialog()
{
//    wacDebugLog("initCottonOrderGoodsItemFormDialog.");
    $("#cottonOrderGoodsItemFormDialog").dialog({
            bgiframe: true,
            modal: true,
            width: 850,
            height: 550,
            autoOpen: false,
            buttons: {},
            zIndex: 100
        });
}

function initCottonOrderGoodsItemForm()
{
    $("#cottonOrderGoodsItemForm").validationEngine();

    $('.wacFormContent .left, .wacFormContent input, .wacFormContent textarea, .wacFormContent select').focus(function(){
        $(this).parents('.wacFormContent').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormContent').removeClass("wacFormOver");
    });

    $('.wacFormContentA .left, .wacFormContentA input, .wacFormContentA textarea, .wacFormContentA select').focus(function(){
        $(this).parents('.wacFormRow').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormRow').removeClass("wacFormOver");
    });


}

function initCottonOrderGoodsItemFormData()
{
    wacShowBlockUILoading("#cottonOrderGoodsItemFormDialog");
    $('#cottonOrderGoodsItem_standard_id, #cottonOrderGoodsItem_factory_id, #cottonOrderGoodsItem_goods_category_id, #cottonOrderGoodsItem_goods_number_unit_code').empty();

    var params = {
        "data_format" :'json'
    };

    $.ajax({
        url: BASE_URL + "cottonOrderGoodsItem/getFormData",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            initCottonOrderGoodsItemFormDataCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function initCottonOrderGoodsItemFormDataCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       alert(jsonData.info.error_info);
   }
   else
    {
        var selectedIndex = 0;

        for(i=0;i<jsonData['items']['standard'].length;i++)
        {
            $('<option value="' + jsonData['items']['standard'][i].key +'">' + jsonData['items']['standard'][i].value +'</option>').appendTo("#cottonOrderGoodsItem_standard_id");
        }

        for(i=0;i<jsonData['items']['unit'].length;i++)
        {
            $('<option value="' + jsonData['items']['unit'][i].key +'">' + jsonData['items']['unit'][i].value +'</option>').appendTo("#cottonOrderGoodsItem_goods_number_unit_code");
        }
   }

   setupCottonOrderGoodsItemFormDefaultValues(jsonData['items']['default']);

   wacHideBlockUI("#cottonOrderGoodsItemFormDialog");

//   wacDebugLog($.dump(jsonData));
}

function setupCottonOrderGoodsItemFormDefaultValues(defaultValueObj)
{
    $("#cottonOrderGoodsItem_cotton_order_id").attr("value", cottonOrderObj.id);
    $("#cottonOrderGoodsItem_cotton_code").attr("innerHTML", cottonOrderObj.code);
    $("#cottonOrderGoodsItem_production_order_code").attr("innerHTML", cottonOrderObj.production_order_code);
    $("#cottonOrderGoodsItem_supplier_name").attr("innerHTML", cottonOrderObj.supplier_name);
    $("#cottonOrderGoodsItem_factory_name").attr("innerHTML", cottonOrderObj.factory_name);

    if(cottonOrderGoodsItemInputMode == wacFormInputMode.add)   // use default values
    {
        $("#cottonOrderGoodsItem_id").attr("value", 0);
        $('#cottonOrderGoodsItem_goods_category_id').flexbox(BASE_URL + 'goodsCategory/GetCottonHashInFormat?data_format=jsonFlexbox&parent=class_cotton', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "goods_category_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $("#cottonOrderGoodsItem_goods_number_unit_code option:[value='"+ defaultValueObj.cotton_unit_code +"']").attr('selected', 'selected');
        $("#cottonOrderGoodsItem_standard_id option:[value='"+ defaultValueObj.standard_id +"']").attr('selected', 'selected');
    }
    else  // use edit obj values
    {
        $('#cottonOrderGoodsItem_goods_category_id').flexbox(BASE_URL + 'goodsCategory/GetCottonHashInFormat?data_format=jsonFlexbox&parent=class_cotton', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: cottonOrderGoodsItemObj.goods_category_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "goods_category_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#cottonOrderGoodsItem_goods_category_id_input').val(cottonOrderGoodsItemObj.goods_category_name);

//        $("#cottonOrderGoodsItem_batch").attr("value", cottonOrderGoodsItemObj.batch);
        $("#cottonOrderGoodsItem_goods_number_unit_price").attr("value", cottonOrderGoodsItemObj.goods_number_unit_price);
        $("#cottonOrderGoodsItem_goods_number").attr("value", cottonOrderGoodsItemObj.goods_number);
        $("#cottonOrderGoodsItem_id").attr("value", cottonOrderGoodsItemObj.id);
        $("#cottonOrderGoodsItem_id_memo").attr("value", cottonOrderGoodsItemObj.memo);

        $("#cottonOrderGoodsItem_goods_number_unit_code option:[value='"+ cottonOrderGoodsItemObj.goods_number_unit_code +"']").attr('selected', 'selected');
        $("#cottonOrderGoodsItem_standard_id option:[value='"+ cottonOrderGoodsItemObj.standard_id +"']").attr('selected', 'selected');
    }

//wacDebugLog($.dump(cottonOrderGoodsItemObj));
//    wacDebugLog($.dump(cottonOrderObj));
//    wacDebugLog($.dump(defaultValueObj));
//    wacDebugLog("cottonOrderGoodsItemInputMode: " + cottonOrderGoodsItemInputMode);

}
/***** init section, end *****/


/**************  interaction section, begin  ***************/

function cottonOrderGoodsItemOpenModuleForm(moduleFormName, moduleName, inputMode, rowid, parentId)
{
    cottonOrderGoodsItemInputMode = inputMode;

    if(parentId === undefined || parentId==0){
        cottonOrderObj = {};
    }
    else
    {
        cottonOrderObj = $("#cottonOrderList").getRowData(parentId);
    }

    if(rowid === undefined || rowid==0){
        cottonOrderGoodsItemObj = {};
    }
    else
    {
        cottonOrderGoodsItemObj = $("#cottonOrderList_" + cottonOrderObj.id + "_t").getRowData(rowid);
    }

    $('#'+moduleFormName).dialog('open');
}

function validateCottonOrderGoodsItemForm()
{
    var validateFlag = true;

    if (!$("#cottonOrderGoodsItemForm").validationEngine({returnIsValid:true}))
    {
        validateFlag = false;
        return validateFlag;
    }

    return validateFlag;
}

function submitCottonOrderGoodsItemForm()
{
    if(!validateCottonOrderGoodsItemForm()){
        return;
    }

    wacShowBlockUILoading("#cottonOrderGoodsItemFormDialog", "处理中...");

    var extraParams = "data_format=json";
    var submitUrl;

    if(cottonOrderGoodsItemInputMode == wacFormInputMode.add){
        submitUrl = BASE_URL + "cottonOrderGoodsItem/add";
    }
    else{
        submitUrl = BASE_URL + "cottonOrderGoodsItem/edit";
    }


    $.ajax({
        url: submitUrl,
//        url: BASE_URL + "test/ajaxTest" ,
        global: true,
        type: "GET",
        data: $("#cottonOrderGoodsItemForm").serialize() + "&" + extraParams,
        dataType: "json",
        success: function(jsonData){
            submitCottonOrderGoodsItemFormCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function submitCottonOrderGoodsItemFormCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#cottonOrderList_" + cottonOrderObj.id + "_t").trigger("reloadGrid");
   }

   wacHideBlockUI("#cottonOrderGoodsItemFormDialog");

//   wacDebugLog($.dump(jsonData));
}

/**************  interaction section, end  ***************/